import type { ThemeMode } from '../types/theme';

// 主题配置常量
export const THEME_CONFIG = {
  LIGHT: 'light' as ThemeMode,
  DARK: 'dark' as ThemeMode,
  STORAGE_KEY: 'theme-mode',
  DEFAULT_THEME: 'light' as ThemeMode,
} as const;

// 主题颜色配置
export const THEME_COLORS = {
  light: {
    primary: '#1890ff',
    success: '#52c41a',
    warning: '#faad14',
    error: '#ff4d4f',
    background: '#ffffff',
    text: '#262626',
    border: '#d9d9d9',
  },
  dark: {
    primary: '#177ddc',
    success: '#49aa19',
    warning: '#d89614',
    error: '#d32029',
    background: '#141414',
    text: '#ffffff',
    border: '#434343',
  },
} as const;

// 主题工具函数
export const themeUtils = {
  // 获取系统主题偏好
  getSystemTheme(): ThemeMode {
    if (typeof window !== 'undefined' && window.matchMedia) {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    return THEME_CONFIG.DEFAULT_THEME;
  },

  // 从本地存储获取主题
  getStoredTheme(): ThemeMode {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem(THEME_CONFIG.STORAGE_KEY);
      return (stored as ThemeMode) || THEME_CONFIG.DEFAULT_THEME;
    }
    return THEME_CONFIG.DEFAULT_THEME;
  },

  // 保存主题到本地存储
  saveTheme(theme: ThemeMode): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem(THEME_CONFIG.STORAGE_KEY, theme);
    }
  },

  // 应用主题到DOM
  applyTheme(theme: ThemeMode): void {
    if (typeof document !== 'undefined') {
      document.body.setAttribute('data-theme', theme);
    }
  },

  // 初始化主题
  initializeTheme(): ThemeMode {
    const theme = this.getStoredTheme();
    this.applyTheme(theme);
    return theme;
  },

  // 监听系统主题变化
  watchSystemTheme(callback: (theme: ThemeMode) => void): (() => void) | null {
    if (typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      const handler = (e: MediaQueryListEvent) => {
        callback(e.matches ? 'dark' : 'light');
      };
      
      mediaQuery.addEventListener('change', handler);
      return () => mediaQuery.removeEventListener('change', handler);
    }
    return null;
  },
}; 